<?php
// +----------------------------------------------------------------------
// | Author: weifashi <605403358@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\actions;
use base\other\Strings;

error_reporting(0);

class Methods {
	
	//替换
	public static function replaceExp($str,$attr=null){
		$userInfo =  request()->userInfo;
        preg_match_all( '/(?<={{)[^}}]+/',$str,$match);
        foreach( $match[0] as $val ){
            $v = "{{{$val}}}";
            switch ($val){
            	//new-------
            	case "base:shop_id"://店铺id
			  		$v = $userInfo['shop_id'] ?: 0;
			  		break; 
			  	//系统--------
                case "base:uuid"://guid
                    $v = Strings::uuid();
                    break;  
                case "base:date"://时间
			  		$v = date( self::getFormat($attr['format']) );
			  		break;      
                case "base:timeStamp"://guid
                    $v = strtotime('now');
                    break;  
                case "base:本人": //当前用户
                    $v = $userInfo['user_name'];
                    break;
                case "base:本人id": //当前用户id
                    $v = $userInfo['user_id'];
                    break;
                case "base:本人guid": //当前用户id
                    $v = $userInfo['user_guid'];
                case "base:本人code": //当前用户id
                    $v = $userInfo['user_code'];
                    break;  
                case "base:orderNo": //订单号
                    $v = Strings::createOrderNo();
                    break;      
                case "base:str6": //密码
                    $v = Strings::getRandomStr(6);
                    break;      
                case "base:str": //密码
                    $v = Strings::getRandomStr();
                    break;             
                case strstr($val,"url:") ? true : false: //字段
                    $v = self::getParam( str_replace("url:","",$val) );
                    break;
            }
            $str = preg_replace("{{{".$val."}}}", $v ,$str);
        }
        return  $str;
	}
	
	/**
	* 获取xml
	* @param  array  $path  路由
	*/
	public static function getXmlFile($path=''){
		
		if (! function_exists('root_path')) {
            function root_path($path = ''){
                return env('root_path').($path ? ltrim($path, DIRECTORY_SEPARATOR) : 
                ltrim($path, DIRECTORY_SEPARATOR));
            }
        }
        
        //当前访问路径
        if( request()->isAjax()  || request()->pathinfo()== 'core/grid/exportExcel'){
            $referer = urldecode( request()->header('referer') );
            $url_path =  str_replace(str_replace("\\","/",env('APP_HOST')),'',$referer);
            $url_path =  str_replace('index.php/','',$url_path);
            $url_path =  str_replace(  str_replace('/','',request()->root())  ,'', $url_path );
        }else{
            $url_path =  request()->pathinfo();
        }
        
        $view_dir_name = explode("/",config('view.view_dir_name'));
        $view = $view_dir_name[count($view_dir_name)-1];
        $url_path =  str_replace('views/',$view.'/',$url_path);
        $url_path = $url_path && $url_path !='/' ? $url_path : '/modules/index/index';
       
        //空路由 默认取当前页面路径的config.xml
        if( empty($path) || !$path ){
            $url='';
            foreach(explode("/",$url_path) as $key => $value){
                if($key != count(explode("/",$url_path))-1 && $value){
                    $url.='/'.$value;
                }
            }
            $path = $url.'/config.xml';
        }
        
        $path = root_path().$path;
        $path = str_replace("index.php","",$path );
        $path = str_replace("///","/", $path );
       
        //返回
        $xml = simplexml_load_file($path);
        if(!$xml    ){
            throw new \think\Exception('找不到xml文件，或xml文件格式错误！'.$path);
        }else{
            return $xml;
        }
	}
	
	
	/**
    * 调用Apl
    * @access private
    * @param string $url 请求路由   			
    * @return  File
    */
	public static function callApi($url,$param=[]) {
	    $url= trim($url);
        $params=array();
        $params['is_action_call']=true;
        if( $index = strpos($url,"?")  ){
            $param = substr($url,$index+1,1000);
            $dataUrlParams = explode("&",$param);
            foreach($dataUrlParams as $paramValue){
                $params[explode("=",$paramValue)[0]] = explode("=",$paramValue)[1];
            }
            $url = substr($url,0,$index);
        }
        if(substr($url,0,1) == "/"){
            $url  = substr($url,1,1000);
        }
        $root = str_replace('/','',request()->root());
        $url = str_replace("Admin","$root",$url);
        $url = str_replace("/","\\",$url);
        $urls = explode('\\',$url);
        $method = $urls[count($urls)-1];
        $class = $urls[count($urls)-2];
        $url = str_replace($class,ucwords($class),$url);
        $url = str_replace("$root\\","$root\controller\\",$url);
        $url = "app\\".str_replace('\\'.$method,"",$url);
        $url = Strings::convertUnderline($url);
        try {
            $reflectionMethod = new \ReflectionMethod($url,$method);
        } catch (\Exception $e) {
            throw new \think\Exception($url.'\\'.$method . '不存在');
        }
        if( !is_array($param) ){
            $param = [];
        }
		return \think\Container::getInstance()->invokeMethod([$url,$method], array_merge($params,$param));
        //return invoke([$url,$method],$params);
	}
	
	/**
    * 获取参数
    */
    public static function getParam($field){
        $params = [];
        $url = request()->header('referer');
        if( $index = strpos($url,"?")  ){
            $dataUrlParams = explode("&",substr($url,$index+1,10000));
            foreach($dataUrlParams as $paramValue){
                $params[explode("=",$paramValue)[0]] = explode("=",$paramValue)[1];
            }
        }
        $v = request()->param("$field")  or "";
        $v = $v ?: $params[$field] ?: "";
        $v = $v ? urldecode($v) : "";
		return $v;
    }
    
    /**
    * 获取日期格式
    * @access private
    * @param string $format  yyyy-MM-dd HH:ii:ss  
    * @return string
    */
	public static function getFormat($format){
		$_format='Y-m-d';
		if(!strpos($format,"d") && $format !="")
			$_format='Y-m';
		if(!strpos($format,"M") && $format !="")
			$_format='Y';
		if(strpos($format,"H"))
			$_format='Y-m-d H';
		if(strpos($format,"mm"))
			$_format='Y-m-d H:i';
		if(strpos($format,"s"))
			$_format='Y-m-d H:i:s';
		if( $format == 'HH' || $format == 'HH:mm' || $format == 'HH:mm:ss')
			$_format='H:i:s';
		return $_format;
	}

}




